import 'dart:io';

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:hc_cure_sdk_flutter/hc_cure_sdk_flutter.dart';
import 'package:hc_cure_sdk_flutter/model/cure/cure.dart';
import 'channel/channel.dart';
import 'channel/channel_mixin.dart';
import '../mixin/device_mixin.dart';

class SDKService with ChannelMixin, DeviceMixin {
  String get host =>
      isDebug ? "http://47.100.120.192" : "https://www.hcxlyun.cn";

  final _box = GetStorage();

  //env
  final _envKey = "com.hc.cure.env";

  //statue
  final _statusKey = "com.hc.cure.login.status";
  bool get isLoggedin => _box.read(_statusKey) ?? false;

  //channel
  final _channelStorageKey = "com.hc.cure.channel.code";

  String _channelCode = "";
  String get channelCode => _channelCode;

  //user
  String get uuid => getDeviceUUID();

  SDKService();
}

extension ServiceEnv on SDKService {
  Future setIsDebug(bool isDebugMode) async {
    await _box.write(_envKey, isDebugMode);
    await _box.save();

    await logout();
    await Future.delayed(2.seconds);
    exit(0);
  }

  bool get isDebug {
    final ret = _box.read<bool>(_envKey);
    return ret ?? false;
  }
}

extension UserServiceEX on SDKService {
  Future login() async {
    if (Platform.isMacOS) return true;
    await Get.find<ChannelService>().refresh();

    if (uuid.isEmpty) {
      final uuid = generateDeviceUUID();
      await saveDeviceID(uuid);
    }

    await HcCureSdkFlutter().login(userID: uuid);
    await _box.write(_statusKey, true);
  }

  Future logout() async {
    await HcCureSdkFlutter().logout();
    await _box.write(_statusKey, false);
  }

  Future initialize() async {
    if (Platform.isMacOS) return;
    //
    _channelCode = await _fetchCode();

    await HcCureSdkFlutter.initialize(_channelCode, customizedHost: host);
  }

  Future<String> _fetchCode() async {
    var code = _box.read<String>(_channelStorageKey);
    code ??= await getDefaultCode();
    return code;
  }

  Future resetCode(String code) async {
    await logout();
    await _box.write(_channelStorageKey, code);
    Get.find<SDKService>().initialize();
  }
}

extension SDKCache on SDKService {
  Future clearCache() => HcCureSdkFlutter().clearCache();

  Future<int> getCacheSize() => HcCureSdkFlutter().getCacheSize();
}

extension SDKCureAudio on SDKService {
  Future<String> fetchCureSolution({
    required Cure cure,
    required Duration duration,
  }) async {
    return fetchCureSolutionWithCureID(cureID: cure.id, duration: duration);
  }

  Future<String> fetchCureSolutionWithCureID({
    required int cureID,
    required Duration duration,
  }) async {
    final solution = await HcCureSdkFlutter().fetchSolution(
      userID: uuid,
      cureID: cureID,
      durationInMins: duration.inMinutes,
      extra: {},
    );
    return solution;
  }
}
